import { createRouter, createWebHistory } from 'vue-router'
import type { RouteRecordRaw } from 'vue-router'

// 路由配置
const routes: Array<RouteRecordRaw> = [
  {
    path: '/',
    redirect: '/tasks'
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('../pages/auth/Login.vue')
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('../pages/auth/Register.vue')
  },
  {
    path: '/tasks',
    name: 'Tasks',
    component: () => import('../pages/tasks/TaskList.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/tasks/my-day',
    name: 'MyDay',
    component: () => import('../pages/tasks/MyDay.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/tasks/:id',
    name: 'TaskDetail',
    component: () => import('../pages/tasks/TaskDetail.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/groups',
    name: 'Groups',
    component: () => import('../pages/groups/GroupManagement.vue'),
    meta: { requiresAuth: true }
  }
]

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token')
  
  // 如果目标路由需要认证
  if (to.matched.some(record => record.meta.requiresAuth)) {
    if (!token) {
      // 没有token，重定向到登录页
      next('/login')
    } else {
      // 有token，允许访问
      next()
    }
  } else {
    // 目标路由不需要认证
    if (token && (to.path === '/login' || to.path === '/register' || to.path === '/')) {
      // 已登录用户访问登录或注册页面，重定向到任务页
      next('/tasks')
    } else {
      // 其他情况允许访问
      next()
    }
  }
})

export default router